package com.zjk.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zjk.ResultObject;
import com.zjk.dto.MemberLoginForm;
import com.zjk.mapper.UserMapper;
import com.zjk.pojo.MemberEntity;
import com.zjk.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: gfk
 * @create: 2022/10/28
 * @Description:
 * @FileName: UserSevice
 * @History:
 * @自定义内容：
 */
@Service
public class UserSevice {
    @Autowired
    UserMapper userMapper;


    /**
     * 根据用户名密码 生成token
     * @param memberLoginForm
     * @return
     */
    public ResultObject<Map> login(MemberLoginForm memberLoginForm) {
        String loginName = memberLoginForm.getLoginName();
        String password1 = memberLoginForm.getPassword();
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MemberEntity::getUsername,loginName)
                .or().eq(MemberEntity::getMobile,loginName)
                        .or().eq(MemberEntity::getIdCardNo,loginName);
        List<MemberEntity> memberEntities = userMapper.selectList(queryWrapper);
        if (memberEntities!=null && memberEntities.size()>0){
            MemberEntity memberEntity = memberEntities.get(0);
            String password = memberEntity.getPassword();

            if (!password1.equals(password)){
                return new ResultObject<>(false,220,"密码输入有误",null);
            }

            Map map = new HashMap();
            map.put("userId",memberEntity.getId());
            map.put("userName",memberEntity.getUsername());
            String token = JwtUtils.createToken(memberEntity.getId().toString(), memberEntity.getUsername(), null);
            return new ResultObject<>(true,200,"登录成功",token);
        }else {
            return new ResultObject<>(false,220,"用户不参与你在",null);
        }
    }
}
